package com.tac.common.Exception;

import com.tac.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@Slf4j
@RestControllerAdvice(annotations = {RestController.class})
public class GlobalException {
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(CosTomException.class)
    public Result<String> exceptionHandele(CosTomException ex){
        String message = ex.getMessage();
        log.info("异常原因：{}",message);
        return Result.error(message);
    }
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> exception(MethodArgumentNotValidException ex){
    //日志记录错误信息
    log.error(Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage());
    //将错误信息返回给前台
    return Result.error(Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage(),400);
    }


    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandele(Exception ex){
        String message = ex.getMessage();
        log.info("异常原因：{}",message);
        return Result.error(message);
    }

}
